﻿using System;
using System. Collections. Generic;
using System. Windows;
using System. Windows. Data;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using Microsoft. Phone. Shell;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using WP7_WebLib. HttpPost;
using NextApp. WP7. Cache. NextApp;

namespace NextApp. WP7. View
{
    public partial class Login : PhoneApplicationPage
    {
        #region Initialize
        public Login( )
        {
            InitializeComponent( );
            this. ApplicationTitle. Text = Config. Instance. blog_title;
            this. Loaded += new RoutedEventHandler(Login_Loaded);
        }

        protected override void OnNavigatedTo(System. Windows. Navigation. NavigationEventArgs e)
        {
            this. txt_UserName. Text = Config. Instance. UserName. EnsureNotNull( );
            this. txt_Password. Password = Config. Instance. Password. EnsureNotNull( );
            base. OnNavigatedTo(e);
        }

        #endregion

        #region 登陆处理
        private void btn_Login_Click(object sender, RoutedEventArgs e)
        {
            if ( NextAppSingleton. Instance. IsReady == false )
            {
                MessageBox. Show("网络还未加载完毕");
                return;
            }
            PostClient client = new PostClient(new Dictionary<string, object>
                {
                    {"username", txt_UserName.Text.Trim()},
                    {"pwd", txt_Password.Password.Trim()},
                    {"keep_login", (bool)check_RememberMe.IsChecked ? "1": "0"},
                })
                {
                    UserAgent = Config. Instance. Http_User_Agent
                };
            //抓取到 Cookie
            client. OnGetCookie += (cookie) =>
                {
                    Config. Instance. Cookie = cookie;
                };
            client. DownloadStringCompleted += (s, e1) =>
                {
					CacheNextApp. Instance. MinusBandwidthCost(new BandwidthCostNextApp { cost = BandwidthCostNextApp. Login_Validate });
                    if ( e1. Error != null )
                    {
                        MessageBox. Show("登入发生错误", "网络错误", MessageBoxButton. OK);
                        return;
                    }
					XElement x;
					try
					{
						x = XElement. Parse(e1. Result). Element("result");
					}
					catch ( Exception )
					{
						return;
					}
                    ApiError _error = new ApiError
                    {
                        errorCode = x. Element("errorCode"). Value. ToInt32( ),
                        errorMessage = x. Element("errorMessage"). Value,
                    };
                    this. ProgressIndicatorIsVisible = false;
                    //处理登陆结果
                    if ( this. ProcessLoginError(_error) )
                    {
                        //检测是否应该保存用户名以及密码
                        this. CheckIsNeedRemember(this. txt_UserName. Text. Trim( ), this. txt_Password.Password. Trim( ));
                        //跳转页面
                        this. GotoPreviouPageOrOther( );
                    }
                };
            //开始异步登陆
            if ( NextAppSingleton.Instance.url_login_validate.IsNotNullOrWhitespace() )
            {
                client. DownloadStringAsync(new Uri(Config. Instance. GetApi(NextAppSingleton. Instance. url_login_validate), UriKind. Absolute));
				CacheNextApp. Instance. AddBandwidthCost(new BandwidthCostNextApp { cost = BandwidthCostNextApp. Login_Validate });
                this. ProgressIndicatorIsVisible = true;
            }
        }

        private void GotoPreviouPageOrOther( )
        {
            if ( this. NavigationContext. QueryString. ContainsKey("next") == false )
            {
                if ( this. NavigationService. CanGoBack )
                {
                    this. NavigationService. GoBack( );
                }
                else
                {
                    this. NavigationService. Navigate(new Uri("/MainPage.xaml", UriKind. Relative));
                }
            }
            else
            {
                switch ( this. NavigationContext. QueryString[ "next" ]. Trim( ) )
                {
                    case "addpost":
                        this. NavigationService. Navigate(new Uri("/View/AddPost.xaml", UriKind. Relative));
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// 处理登陆错误
        /// </summary>
        /// <param name="error">返回结果</param>
        /// <returns>是否发生了登陆错误</returns>
        private bool ProcessLoginError(ApiError error)
        {
            switch ( error.errorCode )
            {
                case 1:
                    MessageBox. Show("登陆成功");
                    return true;
                case 0:
                    MessageBox. Show("用户名或密码错误", "登陆失败", MessageBoxButton. OK);
                    return false;
                case -1:
                    MessageBox. Show("其他错误", "登陆失败", MessageBoxButton. OK);
                    return false;
            }
            return false;
        }
        /// <summary>
        /// 检测是否应该保存用户名以及密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        private void CheckIsNeedRemember(string userName, string password )
        {
            if ( ( bool )this. check_RememberMe. IsChecked )
            {
                Config. Instance. UserName = userName;
                Config. Instance. Password = password;
            }
            else
            {
                Config. Instance. UserName = null;
                Config. Instance. Password = null;
            }
        }

        #endregion

        #region 进度条设置
        void Login_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray. ProgressIndicator = new ProgressIndicator( );
            SystemTray. ProgressIndicator. Text = "登录中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData. Source = this;
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsVisibleProperty, bindingData);
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsIndeterminateProperty, bindingData);
        }
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty. Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(Login),
            new PropertyMetadata(false));
        public bool ProgressIndicatorIsVisible
        {
            get { return ( bool )GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion
    }
}